package com.huluobo.a2207kotlindouyin.videos

import android.animation.Animator.AnimatorListener
import android.content.Intent
import android.util.Log
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.view.animation.AnimationUtils
import android.widget.EditText
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2207kotlindouyin.R
import com.huluobo.a2207kotlindouyin.adapter.CommentAdapter
import com.huluobo.a2207kotlindouyin.adapter.MultiVideoAdapter
import com.huluobo.a2207kotlindouyin.adapter.VideosAdapter
import com.huluobo.a2207kotlindouyin.databinding.FragmentVideoBinding
import com.huluobo.a2207kotlindouyin.live.LiveActivity
import com.huluobo.a2207kotlindouyin.login.LoginActivity
import com.huluobo.base.bean.VideoBean
import com.huluobo.base.mvvm.BaseFragment
import com.huluobo.base.net.Const
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.umeng.socialize.ShareAction
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.parse
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

@AndroidEntryPoint
class VideoFragment : BaseFragment<FragmentVideoBinding, VideoViewModel>() {
    private lateinit var videosAdapter: MultiVideoAdapter
    private var currentPosition = 0
    private lateinit var player: StandardGSYVideoPlayer
    private lateinit var commentAdapter: CommentAdapter
    override fun initData() {
        vm.getVideos(1, 10)
        vm.getVideosSuccess.observe(this) {
            videosAdapter.data.clear()
            videosAdapter.data.addAll(it)
            videosAdapter.notifyDataSetChanged()
        }

        vm.likeVideoSuccess.observe(this) {
            ToastUtils.showLong(it)
            videosAdapter.data[currentPosition].dianzan = 1
            videosAdapter.notifyDataSetChanged()
        }

        vm.noLikeVideoSuccess.observe(this) {
            ToastUtils.showLong(it)
            videosAdapter.data[currentPosition].dianzan = 0
            videosAdapter.notifyDataSetChanged()
        }

        vm.followAuthSuccess.observe(this) {
            ToastUtils.showLong(it)
            videosAdapter.data[currentPosition].guanzhu = 1
            videosAdapter.notifyDataSetChanged()
        }

        vm.getCommentSuccess.observe(this) {
            commentAdapter.data.clear()
            commentAdapter.data.addAll(it)
            commentAdapter.notifyDataSetChanged()
        }

        vm.sendCommentSuccess.observe(this) {
            commentAdapter.data.addAll(0, it)
            commentAdapter.notifyDataSetChanged()

            val editText = videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_et) as EditText
            editText.text.clear()
        }

        vm.collectVideoSuccess.observe(this) {
            ToastUtils.showLong("收藏成功")
        }
    }

    override fun initView() {
        val linearLayoutManager = LinearLayoutManager(requireContext())
        binding.videosRv.layoutManager = linearLayoutManager
        videosAdapter = MultiVideoAdapter()
        binding.videosRv.adapter = videosAdapter
        val pagerSnapHelper = PagerSnapHelper()
        pagerSnapHelper.attachToRecyclerView(binding.videosRv)

        binding.videosRv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                currentPosition = linearLayoutManager.findFirstVisibleItemPosition()
                player =
                    videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_player) as StandardGSYVideoPlayer
//                player.startPlayLogic()
            }
        })

        videosAdapter.addChildClickViewIds(
            R.id.item_videos_like_iv,
            R.id.item_videos_add_iv,
            R.id.item_videos_comment_iv,
            R.id.item_videos_close_iv,
            R.id.item_videos_comment_send_iv,
            R.id.item_videos_collect_iv,
            R.id.item_videos_share_iv,
            R.id.item_videos_live_cl,
            R.id.item_videos_full_cl
        )

        videosAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (SPUtils.getInstance().getString(Const.PARAM_TOKEN).isNullOrEmpty()) {
                val intent = Intent(requireContext(), LoginActivity::class.java)
                startActivity(intent)
            } else {
                val videoBean = videosAdapter.data[position]
                when (view.id) {
                    R.id.item_videos_like_iv -> likeVideo(videoBean)
                    R.id.item_videos_add_iv -> followAuth(videoBean)
                    R.id.item_videos_comment_iv -> openComment(videoBean)
                    R.id.item_videos_close_iv -> closeComment(videoBean)
                    R.id.item_videos_comment_send_iv -> sendComment(videoBean)
                    R.id.item_videos_collect_iv -> collectVideo(videoBean)
                    R.id.item_videos_share_iv -> shareVideo(videoBean)
                    R.id.item_videos_live_cl -> toLive(videoBean)
                    R.id.item_videos_full_cl -> fullScreen()
                }
            }

        }

    }

    private fun fullScreen() {
        player.isRotateViewAuto = true
        player.startWindowFullscreen(requireActivity(), false, false)
    }

    private fun toLive(videoBean: VideoBean) {
        val intent = Intent(requireContext(), LiveActivity::class.java)
        intent.putExtra(Const.PARAM_VIDEO_BEAN, videoBean)
        startActivity(intent)
    }

    private fun shareVideo(videoBean: VideoBean) {
        val umImage = UMImage(requireContext(), videoBean.videomainimg)
        umImage.compressStyle = UMImage.CompressStyle.SCALE

        val umWeb = UMWeb(videoBean.videopath)
        umWeb.title = videoBean.authname
        umWeb.setThumb(umImage)
        umWeb.description = videoBean.caption

        ShareAction(requireActivity())
            .withMedia(umWeb)
            .open()
    }

    private fun collectVideo(videoBean: VideoBean) {
        vm.collectVideo(videoBean)
    }

    private fun sendComment(videoBean: VideoBean) {
        val editText = videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_et) as EditText
        val msg = editText.text.toString().trim()
        if (msg.isNotEmpty()) {
            val map = mutableMapOf<String, Any>()
            map[Const.PARAM_VIDEO_ID] = videoBean.id
            map[Const.PARAM_MSG] = msg
            val json = Gson().toJson(map)
            val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
            vm.sendComment(body)
        }
    }

    private fun closeComment(videoBean: VideoBean) {
        val commentLayout = videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_ll)
        commentLayout?.visibility = View.VISIBLE
        val animOut = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_out)
        animOut.duration = 500
        animOut.interpolator = AccelerateInterpolator()
        animOut.setAnimationListener(object : AnimationListener {
            override fun onAnimationStart(animation: Animation?) {
            }

            override fun onAnimationEnd(animation: Animation?) {
                commentLayout?.visibility = View.GONE
                binding.videosRv.setIntercept(true)
            }

            override fun onAnimationRepeat(animation: Animation?) {
            }
        })
        commentLayout?.startAnimation(animOut)
    }

    private fun openComment(videoBean: VideoBean) {
        binding.videosRv.setIntercept(false)
        val commentLayout = videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_ll)
        commentLayout?.visibility = View.VISIBLE

        val commentRv =
            videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_rv) as RecyclerView

        commentRv.layoutManager = LinearLayoutManager(requireContext())
        commentAdapter = CommentAdapter()
        commentRv.adapter = commentAdapter

        val animIn = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_in)
        animIn.duration = 500
        animIn.interpolator = AccelerateInterpolator()
        animIn.setAnimationListener(object : AnimationListener {
            override fun onAnimationStart(animation: Animation?) {
                vm.getComment(videoBean.id)
            }

            override fun onAnimationEnd(animation: Animation?) {
            }

            override fun onAnimationRepeat(animation: Animation?) {
            }
        })
        commentLayout?.startAnimation(animIn)
    }

    private fun followAuth(videoBean: VideoBean) {
        val map = mutableMapOf<String, String>()
        map[Const.PARAM_AUTHNAME] = videoBean.authname
        val json = Gson().toJson(map)
        val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
        vm.followAuth(body)
    }

    private fun likeVideo(videoBean: VideoBean) {
        if (videoBean.dianzan == 0) {
            vm.likeVideo(videoBean.id)
        } else {
            vm.noLikeVideo(videoBean.id)
        }
    }
}